package com.share.four.netty.heartBeat;

import java.util.HashMap;

import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;

import com.share.four.netty.heartBeat.entity.ReqInfo;

/*
 * ChannelHandlerAdapter.class--->适配器设计模式：目的是不用重写接口中的每个方法，只重写需要的
 */
public class ServerHandler extends ChannelHandlerAdapter{
	
	public static final HashMap<String, Object> IP_MAP = new HashMap<>();
	public static final String AUTH_SUCCESS = "auth success!";
	public static final String AUTH_FAIL = "auth fail!";
	
	static{
		IP_MAP.put("192.168.31.164", "1234");
	}
	
	/* 
	 * description： 在不接受任何请求时, 只是在连接被创建时，会执行此方法
	 */
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("server channel active");
	}

	/* 
	 * @description: 每当从客户端收到新的数据时，这个方法会在收到消息时被调用
	 * msg: client端发送过来的数据
	 * ctx: server端与client端的channel
	 */
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

		try {
			if (msg instanceof String) {
				auth(ctx, msg);
				
			}else if (msg instanceof ReqInfo) {
				ReqInfo reqInfo = (ReqInfo)msg;
				System.out.println(reqInfo);
				ctx.writeAndFlush("receive heartBeat...");
			} else {
				System.out.println(msg);
			}
			
		} finally {
			//DISCARD服务(丢弃服务，指的是会忽略所有接收的数据的一种协议)
			ReferenceCountUtil.release(msg);
		}

	}

	private void auth(ChannelHandlerContext ctx, Object msg) {
		String req = (String)msg;
		String[] result = req.split(",");
		if (result[1].equals(IP_MAP.get(result[0]))) {
			ctx.writeAndFlush(AUTH_SUCCESS);
			System.out.println(AUTH_SUCCESS);
		} else {
			ctx.writeAndFlush(AUTH_FAIL).addListener(ChannelFutureListener.CLOSE);
			System.out.println(AUTH_FAIL);
		}
		
	}

	/* 
	 * @description: 当Netty由于IO错误或者处理器在处理事件时抛出的异常时,该方法被调用
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}


}
